using System;
using WpfLob.Frame;
using System.Collections.Generic;
using WpfLob.Projects.DataModel;
using System.Collections.ObjectModel;
using System.Windows.Input;
using WpfLob.Commands;
using WpfLob.Projects.ViewModel;

namespace WpfLob.Menu.ViewModel
{
    public class ProjectsViewModel : Pane
    {
        private ProjectDataSource _projectDataSource;
        private ProjectsNavigationModel _navigation;
        private ObservableCollection<ProjectItemViewModel> _projects = new ObservableCollection<ProjectItemViewModel>();

        public ProjectsViewModel(IPresenter presenter)
            : base(presenter)
        {
            _projectDataSource = new ProjectDataSource();
            _navigation = new ProjectsNavigationModel();

            IEnumerable<Project> projects = _projectDataSource.GetProjects();
            foreach (Project project in projects)
                _projects.Add(new ProjectItemViewModel(project));
        }

        public override string Title
        {
            get { return "Projects"; }
        }

        public IEnumerable<ProjectItemViewModel> Projects
        {
            get { return _projects; }
        }

        public ProjectItemViewModel SelectedProject
        {
            get
            {
                return _navigation.SelectedProject != null
                    ? new ProjectItemViewModel(_navigation.SelectedProject)
                    : null;
            }
            set { _navigation.SelectedProject = value.Project; }
        }

        public ICommand NewProject
        {
            get
            {
                return new SimpleCommand(() =>
                {
                    Project newProject = new Project();
                    _projectDataSource.SaveProject(newProject);
                    _projects.Add(new ProjectItemViewModel(newProject));
                    _navigation.SelectedProject = newProject;
                });
            }
        }

        public ICommand EditProject
        {
            get
            {
                return new SimpleCommand(() => Presenter.Show(new ProjectViewModel(Presenter, _navigation.SelectedProject)));
            }
        }

        public ICommand DeleteProject
        {
            get
            {
                return new SimpleCommand(() =>
                {
                    _projectDataSource.DeleteProject(_navigation.SelectedProject);
                });
            }
        }
    }
}
